//
//  EasyTakePicDetailViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/29.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "EasyTakePicDetailViewModel.h"

#import "SSPPublishContentItemViewModel.h"
#import "CommonGoodCellModel.h"
#import "StwxCommentItemViewModel.h"

#import "TransmitsListData.h"

@interface EasyTakePicDetailViewModel()

@property (nonatomic, readwrite, strong) RACCommand* requestDataCmd;

@property (nonatomic, readwrite, strong) RACCommand* selectCmd;
@property (nonatomic, readwrite, strong) RACCommand* transmitCmd;
@property (nonatomic, readwrite, strong) RACCommand* praiseCmd;
@property (nonatomic, readwrite, strong) RACCommand* commentCmd;
@property (nonatomic, readwrite, strong) RACCommand* delCmd;

@end

@implementation EasyTakePicDetailViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    self.isMyself = NO;
    self.isNeedListRefresh = NO;
    
    self.lastPage = 999;
    self.shouldMultiSections = YES;
    
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = YES;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = YES;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    
    /// 选中
    //    self.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(ArticleItemViewModel * itemViewModel) {
    //        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
    //                [subscriber sendNext:itemViewModel];
    //                [subscriber sendCompleted];
    //            });
    //            return nil;
    //        }];
    //    }];
    /// 允许并行执行
    self.selectCmd.allowsConcurrentExecution = NO;
    
    self.tableTabIndex = 0;
    
    self.shareDatas = [NSMutableArray array];
    self.goodDatas = [NSMutableArray array];
    self.commentDatas = [NSMutableArray array];
    
    SSPDetailData* sspDetailData = self.params[@"SSPDetailData"];
    self.sspPublishContentIVM = [[SSPPublishContentItemViewModel alloc] initWithData:sspDetailData cellHeight:100.0f];
    self.sspPublishContentIVM.isShowTags = NO;
    self.sspTabsCM = [[SSPTabsCellModel alloc] initWithData:sspDetailData cellHeight:100.0f];
    self.isPraise = sspDetailData.isPraise;
    
    [[[RACObserve(self, tableTabIndex) distinctUntilChanged] flattenMap:^RACStream *(id value) {
        
        @strongify(self);
        
        self.page = 0;
        self.lastPage = 999;
        
        return [self.requestRemoteDataCommand execute:@(self.page)];
    }] subscribeNext:^(id x) {
        
        @strongify(self);
        
        self.page ++;
    }];
    
    self.transmitCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                        {
                            @strongify(self);
                            
                            UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
                            
                            SSPDetailData* sspDetailData = self.params[@"SSPDetailData"];
                            
                            return [self requestTransmitSignal:um.userData.userID circleID:sspDetailData.circleID type:@"1"];
                        }];
    
    self.praiseCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                        {
                            @strongify(self);
                            
                            UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
                            
                            SSPDetailData* sspDetailData = self.params[@"SSPDetailData"];
                            
                            return [self requestPraiseSignal:um.userData.userID circleID:sspDetailData.circleID type:@"2"];
                        }];
    
    self.commentCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                      {
                          @strongify(self);
                          
                          UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
                          
                          SSPDetailData* sspDetailData = self.params[@"SSPDetailData"];
                          
                          NSString* content = input;
                          
                          if ([NSString mh_isBlankString:content])
                          {
                              return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"评论内容不能为空"}]];
                          }
                          
                          return [self requestCommentSignal:um.userData.userID circleID:sspDetailData.circleID type:@"3" content:content];
                      }];
    
    self.delCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
        
        SSPDetailData* sspDetailData = self.params[@"SSPDetailData"];
        
        return [self _requestDelSignal:um.userData.userID circleID:sspDetailData.circleID];
    }];
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self)
        
        SSPDetailData* detailData = self.sspPublishContentIVM.data;
        NSString* type = @"";
//        if (self.tableTabIndex == 0) type = @"1";
        if (self.tableTabIndex == 0) type = @"3";
        if (self.tableTabIndex == 1) type = @"2";
        
        NSInteger reqPage = page+1;
        
        NSDictionary* postData = interface_param_circleparameter(detailData.circleID, type, @(reqPage), @(List_PageSize));
        
        NSLog(@"请求随手拍列表数据 : %@", [postData plistString]);
        
        /// 转化数据
        @weakify(self);
        
        [[AFNetWorkUtils racPOSTWthURL:url_interface_circleparameter params:postData] subscribeNext:^(id x)
         {
             @strongify(self)
             
             TransmitsListData* tsListData = [TransmitsListData modelWithJSON:x];
             
             NSArray* viewModels = @[];
             
             if (tsListData && tsListData.datas)
             {
//                 if (self.tableTabIndex == 0)
//                 {
//                     viewModels = [tsListData.datas.rac_sequence map:^CommonGoodCellModel *(TransmitListData* tsListData)
//                                   {
//                                       @strongify(self);
//
//                                       //计算当前cellheight
//                                       CommonGoodCellModel *itemViewModel = [[CommonGoodCellModel alloc] initWithData:tsListData cellHeight:self.cellHeight];
//
//                                       return itemViewModel;
//                                   }].array;
//                 }
//                 else
                 if (self.tableTabIndex == 0)
                 {
                     viewModels = [tsListData.datas.rac_sequence map:^StwxCommentItemViewModel *(TransmitListData* tsListData) {
                         @strongify(self);
                         
                         //计算当前cellheight
                         StwxCommentItemViewModel *itemViewModel = [[StwxCommentItemViewModel alloc] initWithData:tsListData cellHeight:self.cellHeight];
                         
                         return itemViewModel;
                     }].array;
                 }
                 else if (self.tableTabIndex == 1)
                 {
                     viewModels = [tsListData.datas.rac_sequence map:^CommonGoodCellModel *(TransmitListData* tsListData) {
                         @strongify(self);
                         
                         //计算当前cellheight
                         CommonGoodCellModel *itemViewModel = [[CommonGoodCellModel alloc] initWithData:tsListData cellHeight:self.cellHeight];
                         
                         return itemViewModel;
                     }].array;
                 }
             }
             
             if (viewModels == nil)
                 viewModels = @[];
             
             if (viewModels.count < List_PageSize)
             {
                 self.lastPage = self.page;
             }
             
             if (self.shouldPullUpToLoadMore)
             {
                 if (0 == page)
                 {
                     self.dataSource = @[@[self.sspPublishContentIVM, self.sspTabsCM], viewModels];
                 }
                 else
                 {
                     if (self.dataSource == nil)
                     {
                         self.dataSource = @[@[self.sspPublishContentIVM, self.sspTabsCM], viewModels];
                     }
                     else
                     {
                         self.dataSource = @[@[self.sspPublishContentIVM, self.sspTabsCM], [self.dataSource[1] arrayByAddingObjectsFromArray:viewModels]];
                     }
                 }
             }
             else
             {
                 self.dataSource = @[@[self.sspPublishContentIVM, self.sspTabsCM], viewModels];
             }
             
             [subscriber sendNext:x[SUCommandSysMessageKey]];
             [subscriber sendCompleted];
         }   error:^(NSError *error) {
             //错误处理
             
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal *)requestTransmitSignal:(NSString*)userID circleID:(NSString*)circleID type:(NSString*)type
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self)
        
        @weakify(self);
        NSDictionary* postData = interface_param_transmit(userID, circleID, type);
        
        [[AFNetWorkUtils racPOSTWthURL:url_interface_transmit params:postData] subscribeNext:^(id x)
         {
             @strongify(self)
             
             NSDictionary* result = x;
             
             [subscriber sendNext:result[SUCommandSysMessageKey]];
             [subscriber sendCompleted];
         }   error:^(NSError *error) {
             //错误处理
             
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal *)requestPraiseSignal:(NSString*)userID circleID:(NSString*)circleID type:(NSString*)type
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self)
        
        @weakify(self);
        NSDictionary* postData = interface_param_praise(userID, circleID, type);
        
        [[AFNetWorkUtils racPOSTWthURL:url_interface_praise params:postData] subscribeNext:^(id x)
         {
             @strongify(self)
             
             NSDictionary* result = x;
             
             self.isPraise = !self.isPraise;
             
             SSPListData* listData = self.params[@"SSPListData"];
             listData.ifPraise = self.isPraise ? @"1" : @"2";
             
             [subscriber sendNext:result[SUCommandSysMessageKey]];
             [subscriber sendCompleted];
         }   error:^(NSError *error) {
             //错误处理
             
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal *)requestCommentSignal:(NSString*)userID circleID:(NSString*)circleID type:(NSString*)type content:(NSString*)content
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self)
        
        @weakify(self);
        NSDictionary* postData = interface_param_comment(userID, circleID, type, content);
        
        [[AFNetWorkUtils racPOSTWthURL:url_interface_comment params:postData] subscribeNext:^(id x)
         {
             @strongify(self)
             
             NSDictionary* result = x;
             
             [subscriber sendNext:result[SUCommandSysMessageKey]];
             [subscriber sendCompleted];
         }   error:^(NSError *error) {
             //错误处理
             
             NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"评论失败";
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal*)_requestDelSignal:(NSString*)userID circleID:(NSString*)circleID
{
    @weakify(self);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self)
        
        @weakify(self);
        NSDictionary* postData = interface_param_circleDel(userID, circleID);
        
        [[AFNetWorkUtils racPOSTWthURL:url_interface_circleDel params:postData] subscribeNext:^(id x)
         {
             @strongify(self)
             
             NSDictionary* result = x;
             
             self.isNeedListRefresh = YES;
             
             [subscriber sendNext:result[SUCommandSysMessageKey]];
             [subscriber sendCompleted];
         }   error:^(NSError *error) {
             //错误处理
             
             NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"删除失败";
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

@end
